package org.zpmis.common.utils.language;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.zpmis.configurer.LanguageLocaleResolver;
import org.zpmis.common.enums.LangEnum;

import java.util.Locale;

/**
 * 国际化工具类
 * @author LENOVO
 */
@Slf4j
public class LanguageUtils {

    /**
     * 获取单个国际化翻译值
     */
    public static String getMessage(String key) {
        return getMessage(key, null, null, null);
    }

    public static String getMessage(String key, Object[] args) {
        return getMessage(key, args, "",null);
    }

    public static String getMessage(String key, Object[] args,String lang) {
        return getMessage(key, args, "",lang);
    }

    private static String getMessage(String code, Object[] args, String defaultMessage,String lang) {
        Locale locale = null;
        if(lang == null){
            locale = LanguageLocaleResolver.localeResolver();
        }else{
            LangEnum langEnum = LangEnum.getByCode(lang) == null ? LangEnum.EN : LangEnum.getByCode(lang);
            locale = new Locale(langEnum.language(),langEnum.area());
        }
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("i18n/messages");
        messageSource.setDefaultEncoding("UTF-8");
        String content;
        try{
            content = messageSource.getMessage(code, args, locale);
        }catch (Exception e){
            log.info("获取国际化提示消息失败Message:{},使用默认提示语言",e.getMessage());
            content = defaultMessage;
        }
        return content;
    }

}